from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.contenttypes.models import ContentType
from .models import Comment, Message, Notification
def create_notification(user, verb, target=None, actor=None, data=None):
    """
    创建通知工具函数
    :param user: 接收用户
    :param verb: 通知类型
    :param target: 目标对象（可选）
    :param actor: 触发用户（可选）
    :param data: 附加数据（可选）
    """
    target_ct = ContentType.objects.get_for_model(target) if target else None
    Notification.objects.create(
        user=user,
        verb=verb,
        target_ct=target_ct,
        target_id=target.id if target else None,
        actor=actor,
        data=data or {}
    )
@receiver(post_save, sender=Comment)
def create_comment_notification(sender, instance, created, **kwargs):
    if created:
        # 通知被评论对象的所有者
        if instance.parent:  # 如果是回复评论
            Notification.objects.create(
                recipient=instance.parent.user,
                sender=instance.user,
                verb='reply',
                target=instance
            )
        else:  # 如果是新评论
            content_type = ContentType.objects.get_for_model(instance.content_object)
            Notification.objects.create(
                recipient=instance.content_object.user,  # 假设被评论对象有 user 字段
                sender=instance.user,
                verb='comment',
                target=instance.content_object
            )

@receiver(post_save, sender=Message)
def create_message_notification(sender, instance, created, **kwargs):
    if created:
        Notification.objects.create(
            recipient=instance.receiver,
            sender=instance.sender,
            verb='message',
            target=instance
        )
